package com.imooc.service.impl;

import com.imooc.enums.OrderStatusEnum;
import com.imooc.enums.YesOrNo;
import com.imooc.mapper.OrderItemsMapper;
import com.imooc.mapper.OrderStatusMapper;
import com.imooc.mapper.OrdersMapper;
import com.imooc.pojo.*;
import com.imooc.pojo.bo.SubmitOrderBO;
import com.imooc.pojo.vo.MerchantOrdersVO;
import com.imooc.pojo.vo.OrdersVO;
import com.imooc.service.AddressService;
import com.imooc.service.ItemService;
import com.imooc.service.OrderService;
import com.imooc.utils.DateUtil;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {


    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderItemsMapper orderItemsMapper;

    @Autowired
    private OrderStatusMapper orderStatusMapper;

    @Autowired
    private Sid sid;

    @Autowired
    private AddressService addressService;

    @Autowired
    private ItemService itemService;

    @Override
    public OrdersVO createOrder(SubmitOrderBO submitOrderBO) {

        String userId=submitOrderBO.getUserId();
        String addressId=submitOrderBO.getAddressId();
        String itemSpecIds=submitOrderBO.getItemSpecIds();
        Integer payMethod=submitOrderBO.getPayMethod();
        String leftMsg=submitOrderBO.getLeftMsg();
        //包邮费用设置为0
        Integer postAmount=0;

        UserAddress address=addressService.queryUserAddres(userId,addressId);

        //1.新订单数据保存
        String orderId=sid.nextShort();

        Orders orders=new Orders();
        orders.setId(orderId);
        orders.setUserId(userId);
        orders.setReceiverName(address.getReceiver());
        orders.setReceiverAddress(address.getProvince()+" "+
                                  address.getCity()+" "+address.getDistrict()
                                  +" "+address.getDetail());
        orders.setReceiverMobile(address.getMobile());
//       orders.setTotalAmount();
//       orders.setRealPayAmount();
        orders.setPostAmount(postAmount);

        orders.setPayMethod(payMethod);

        orders.setLeftMsg(leftMsg);

        orders.setIsComment(YesOrNo.NO.type);

        orders.setIsDelete(YesOrNo.NO.type);

        orders.setCreatedTime(new Date());

        orders.setUpdatedTime(new Date());

        //2.循环根据itemSpecIds保存订单商品信息表
        String itemSpecIdArr[] = itemSpecIds.split(",");
        Integer totalAmount=0;  //商品原价累计
        Integer realPayAmount=0; //优惠后的实际支付价格累计
        for (String itemSpecId:itemSpecIdArr){

            //TODO 整合Redis后，商品购买数量重新从redis的购物车中获取
            int buyCounts=1;

            //2.1根据规格Id，查询规格的具体信息，主要获取价格
            ItemsSpec itemsSpec = itemService.queryItemSpecById(itemSpecId);
            totalAmount+=itemsSpec.getPriceNormal()*buyCounts;
            realPayAmount+=itemsSpec.getPriceDiscount()-buyCounts;

            //2.2根据商品id获得商品信息以及商品图片
            String itemId = itemsSpec.getItemId();

            Items item =itemService.queryItemById(itemId);
            String imgUrl = itemService.queryItemMainImgById(itemId);

            //2.3循环保存子订单数据到数据库
            String subOrderId=sid.nextShort();
            OrderItems subOrderItem =new OrderItems();
            subOrderItem.setId(subOrderId);
            subOrderItem.setOrderId(orderId);
            subOrderItem.setItemId(itemId);
            subOrderItem.setItemName(item.getItemName());
            subOrderItem.setItemImg(imgUrl);
            subOrderItem.setBuyCounts(buyCounts);
            subOrderItem.setItemSpecId(itemSpecId);
            subOrderItem.setItemSpecName(itemsSpec.getName());
            subOrderItem.setPrice(itemsSpec.getPriceDiscount());

            orderItemsMapper.insert(subOrderItem);

            //2.4在用户提交订单以后，规格表中需要扣除库存
            itemService.decreaseItemSpecStock(itemSpecId,buyCounts);


        }
        orders.setTotalAmount(totalAmount);
        orders.setRealPayAmount(realPayAmount);
        ordersMapper.insert(orders);

        //3.保存订单状态表
        OrderStatus waitPayOrderStatus =new OrderStatus();
        waitPayOrderStatus.setOrderId(orderId);
        waitPayOrderStatus.setOrderStatus(OrderStatusEnum.WAIT_PAY.type);
        waitPayOrderStatus.setCreatedTime(new Date());
        orderStatusMapper.insert(waitPayOrderStatus);

        //4.构建商户订单用于传给支付中心
        MerchantOrdersVO merchantOrdersVO=new MerchantOrdersVO();
        merchantOrdersVO.setMerchantOrderId(orderId);
        merchantOrdersVO.setMerchantUserId(userId);
        merchantOrdersVO.setAmount(realPayAmount+postAmount);
        merchantOrdersVO.setPayMethod(payMethod);

        //5.构建自定义订单vo
        OrdersVO ordersVO=new OrdersVO();
        ordersVO.setOrderId(orderId);
        ordersVO.setMerchantOrdersVO(merchantOrdersVO);

        return ordersVO;
    }


    @Override
    public void updateOrderStatus(String orderId, Integer orderStatus) {

        OrderStatus paidStatus=new OrderStatus();
        paidStatus.setOrderId(orderId);
        paidStatus.setOrderStatus(orderStatus);
        paidStatus.setPayTime(new Date());

        orderStatusMapper.updateByPrimaryKeySelective(paidStatus);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public OrderStatus queryOrderStatusInfo(String orderId) {
        return orderStatusMapper.selectByPrimaryKey(orderId);
    }


    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public void closerOrder() {

        //查询所有未付款订单，判断时间是否超市（1天）,超时则关闭交易
        OrderStatus queryOrder=new OrderStatus();
        queryOrder.setOrderStatus(OrderStatusEnum.WAIT_PAY.type);
        List<OrderStatus> list =orderStatusMapper.select(queryOrder);
        for (OrderStatus os:list){
            //获得订单时间
            Date createTime=os.getCreatedTime();
            //和当前时间对比
            int days = DateUtil.daysBetween(createTime,new Date());
            if (days>=1){
                //超过一天关闭订单
                doCloseOrder(os.getOrderId());
            }
        }
    }
    void doCloseOrder(String orderId){
        OrderStatus close=new OrderStatus();
        close.setOrderId(orderId);
        close.setOrderStatus(OrderStatusEnum.CLOSE.type);
        close.setCreatedTime(new Date());
        orderStatusMapper.updateByPrimaryKeySelective(close);

    }
}
